<?php

class Profile extends Public_Controller {

    public $aUser;
    public $bIsSuccess;
    public $aCaptcha;

    public function __construct() {
        parent::__construct();
        $this->_load();
    }

    public function index() {
        if (($this->aUser = $this->input->post('user')) && $this->input->is_ajax_request()) {
            $this->_register();
        }
    }

    private function _register() {
        $aConfig = $this->_getRuleRegister();
        $this->validation->set_rules($aConfig);
        $this->validation->set_message('is_unique', $this->lang->line("phrase var='user.this_email_is_already_existed'"));
        if ($this->validation->run() == FALSE) {
            $this->smessage = validation_errors();
            $this->return_fail_json($this->aUser, $this->smessage);
            return false;
        }

        //Check captcha
//        var_dump($this->session->userdata($this->config->item('captcha_name')));
//        if(!(bool)$this->check_captcha($this->aUser)){
//            $this->smessage = $this->lang->line("phrase var='user.captcha_not_match'");
//            $this->return_fail_json($this->aUser, $this->smessage);
//            return false;
//        }

        //Send email when register successfully.
        if ((bool) $oUser = $this->user->register($this->aUser)) {
           $oUser->email = trim($this->aUser['email']);
            //Send email active account.
            $this->mail->sendRegister($oUser, $this->_slang_name);
        }

        //Output message when register successfully.
        $this->smessage = $this->lang->line("phrase var='user.register_successfully'");
        unset($this->aUser['password']);
        unset($this->aUser['repassword']);
        $this->return_success_json($this->aUser, $this->smessage);
    }

    private function _load() {
        $this->load->helper(array('url', 'form'));
        $this->load->model('user');
        $this->load->model('mail', 'mail', FALSE, 'mail');
        $this->lang->load('public/general', $this->_slang_name);
        $this->lang->load('public/register', $this->_slang_name);
        $this->load->library('form_validation', NULL, 'validation');
        $this->aUser = array();
        $this->bIsSuccess = -1;
    }

    private function _replacePhrase() {
        $this->finalize();
        $this->fill_phrase('confirm_account', $this->_adata, $this->lang->language);
    }

    private function _getRuleRegister() {
        return array(
            array(
                'field' => 'user[email]',
                'label' => 'Email',
                'rules' => 'trim|required|valid_email|matches[user[reemail]]|is_unique[user.email]'
            ),
            array(
                'field' => 'user[reemail]',
                'label' => $this->lang->line("phrase var='user.Re_enter_email'"),
                'rules' => 'trim'
            ),
            array(
                'field' => 'user[password]',
                'label' => $this->lang->line("phrase var='user.password"),
                'rules' => 'trim|required|min_length[5]|matches[user[repassword]]|alpha_dash'
            ),
            array(
                'field' => 'user[repassword]',
                'label' => $this->lang->line("phrase var='user.confirm_password'"),
                'rules' => 'trim'
            ),
            array(
                'field' => 'user[captcha]',
                'label' => 'Captcha',
                'rules' => 'trim|require'
            )
        );
    }

    public function finalize() {
        $this->lang->load('public/register', $this->_slang_name);
        $this->_adata['message'] = $this->smessage;
        $this->_adata['user'] = $this->aUser;
        $this->_adata['bIsSuccess'] = $this->bIsSuccess;
    }
    
    public function confirm($sKey = null) {
        if (empty($sKey)) {
            redirect('/product/list_product');
            return false;
        }

        $iReturn = $this->user->activeAccount($sKey);

        switch ($iReturn) {
            case ACTIVED:
                redirect('/product/list_product');
                break;
            case ACTIVE_NOSUCCESS:
                $this->smessage = $this->lang->line("phrase var='user.active_unsuccessfully'");
                break;
            case ACTIVE_SUCCESS: {
                    $this->smessage = $this->lang->line("phrase var='user.active_successfully'");
                    $this->mail->sendCompleteRegister();
                }
                break;
            default : break;
        }

        $this->_replacePhrase();
    }
    
    public function requestNewPassword() {
        if (!(bool) $this->input->is_ajax_request()) {
            $this->_redirect_index();
        }

        $sEmail = $this->input->post('email');

        if (!(bool) $this->user->isExistedEmail($sEmail)) {
            $this->return_fail_json(array('email' => $sEmail), $this->lang->line("phrase var='user.this_email_is_not_existed'"));

            return false;
        }

        if ((bool) $this->mail->sendForgetPassword($sEmail, $this->_slang_name)) {
            $this->return_success_json(array('email' => $sEmail), $this->lang->line("phrase var='user.send_email_change_password_success'"));

            return true;
        }

        $this->return_fail_json(array('email' => $sEmail), $this->lang->line("phrase var='user.cannot_send_email_change_password'"));
    }

    public function restorePassword($sCode = '', $iTime = 0) {
        if (empty($sCode) || empty($iTime)) {
            $this->_redirect_index();
        }

        $this->_adata['sCode'] = $sCode;
        $this->_adata['iTime'] = $iTime;

        //Check if user is logining.
//        if ($this->user->isLogin()) {
        if ($this->user->isLogin()) {
            $this->_adata['sCode'] = $sCode;
            $this->_adata['iTime'] = $iTime;
            $this->finalize();
            $this->fill_phrase('ask_logout', $this->_adata, $this->lang->language);

            return false;
        }
        // Compare with time and code
        if (!(bool) $this->user->isValidChangePassword($sCode, $iTime)) {
            $this->_redirect_index();
        }

        $this->changePassword($sCode, $iTime);
        $this->finalize();
        $this->fill_phrase('request_change_password', $this->_adata, $this->lang->language);

        return true;
    }

    public function changePassword($sCode = '', $iTime = 0) {
        if (empty($sCode) || empty($iTime)) {
            return false;
        }

        if (!(bool) $aPassword = $this->input->post('password')) {
            return false;
        }

        //If input a valid password....
        $aConfig = $this->_getRulesChangePassword();
        $this->validation->set_rules($aConfig);

        if ($this->validation->run() == FALSE) {
            $this->smessage = validation_errors();

            return false;
        }

        if ((bool) $this->user->changePassword($aPassword, $sCode, $iTime)) {
            //Redirect to page index list product 
            $this->_redirect_index();
        }
    }

    public function destroyRestorePassword($sCode = '', $iTime = 0) {
        if (empty($sCode) || empty($iTime)) {
            $this->_redirect_index();
        }

        //Reset change password...
        if ((bool) $this->user->resetChangePassword($sCode, $iTime)) {
            $this->finalize();
            $this->fill_phrase('destroy_change_password', $this->_adata, $this->lang->language);
        }

        //In case if we haven't been yet changed password.
        $this->_redirect_index();
    }

    public function logoutChangePass($sCode = '', $iTime = 0) {
        if (empty($sCode) || empty($iTime)) {
            $this->_redirect_index();
        }
        
        if($this->user->logout()){
            redirect("user/profile/restorePassword/{$sCode}/{$iTime}");
        }
        
        return false;
    }

    private function _getRulesChangePassword() {
        return array(
            array(
                'field' => 'password[new_password]',
                'label' => $this->lang->line("phrase var='user.password"),
                'rules' => 'trim|required|min_length[5]|alpha_dash'
            ),
            array(
                'field' => 'password[confirm_password]',
                'label' => $this->lang->line("phrase var='user.confirm_password'"),
                'rules' => 'trim|matches[password[new_password]]'
            )
        );
    }
}

?>
